package com.sudu.controller.interceptor;

import com.sudu.dao.TokenUtil;
import com.sudu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Autowired
    private UserService userService ;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取token
        String token = request.getHeader(TokenUtil.tokenHeader);
        if (null==token) {
            System.out.println("没有携带token");
            return false;
        }
        try {
            TokenUtil.getTokenBody(token);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("token有问题 TokenUtil.getTokenBody(token);");
            return false;
        }
        try {
            // 通过token拿到userId
            int id = Integer.parseInt(TokenUtil.getUserId(token));
            // token拿到的phone == 通过userId查询到的phone ， 则返回true
           if ( TokenUtil.getPhone(token).equals(userService.finePhoneByUid(id))  ) {
               return true;
           } else {
               System.out.println("TokenUtil.getPhone(token)=========" + TokenUtil.getPhone(token));
               System.out.println("userService.finePhoneByUid(id)=========" + userService.finePhoneByUid(id));
               System.out.println("token有问题=========================") ;
               return false;
           }

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("token有问题");
            return false;
        }

    }


}
